const xss=require('xss')
const { exec } = require('../db/mysql')

const getList=(author,keyword)=>{

    let sql=`select * from blog where 1=1`;
    if(author){
        sql+=` and author='${author}'`;
    }
    if(keyword){
        sql+=` and title like '%${keyword}%'`;
    }
    sql += ` order by createtime desc;`

    //返回 promise
    return exec(sql)
}

const getDetail=(id)=>{
    const sql=`select * from blog where id='${id}'`;
    return exec(sql).then(rows=>{
        return rows[0];
    })
}

const newBlog=(blogData={})=>{
    //blogData是一个博客对象，包含title content 属性
    // console.log('newBlog blogData...',blogData)
    const title=xss(blogData.title);
    const content=blogData.content;
    const author=blogData.author;
    const createTime=Date.now();
    const sql=`
      insert into blog (title,content,createtime,author)
       values ('${title}','${content}','${createTime}','${author}')
    `;
    return exec(sql).then(insertData=>{
        // console.log('insertData is',insertData)
        return{
            id:insertData.insertId
        }
    })
    // return{
    //     id:3 //表示新建博客，插入到数据表里面的id
    // }
}

const updateBlog=(id,blogData)=>{
    //id就是要更新博客的id
    //blogData是一个博客对象，包含title content 属性
    const title=blogData.title;
    const content=blogData.content;
    const sql=`
        update blog set title='${title}',content='${content}' where id=${id}
    `;
    return exec(sql).then(updateData=>{
        // console.log('insertData is',updateData)
        if(updateData.affectedRows>0){
            return true
        }
        return false
    })
    // console.log('update blog',id,blogData)
    // return true
}

const delBlog=(id,author)=>{
    //id就是要删除博客的id
    const sql=`delete from blog where id='${id}' and author='${author}';`;
    return exec(sql).then(delData=>{
        // console.log('insertData is',updateData)
        if(delData.affectedRows>0){
            return true
        }
        return false
    }) 
    // return true
}

module.exports={
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}